package test;

import java.util.ArrayList;
import java.util.TimerTask;

import domain.Auction;

import tcpClient.ClientTestInterface;

public class BidAuctionTimerTask extends TimerTask {

	private Auction auction;
	private LoadTestComponent loadTestComponent;
	private ClientTestInterface client; 

	public BidAuctionTimerTask(LoadTestComponent loadTestComponent,	ClientTestInterface client) {
		super();
		this.loadTestComponent = loadTestComponent;
		this.client = client;
	}

	@Override
	public void run() {
		client.sendCommand("!list");
		String output = client.response();
		ArrayList<BidObject> list = new ArrayList<BidObject>();
		while(!output.equals("*endlist*") && !output.equals("No auctions running.")){
			if(Character.isDigit(output.charAt(0))) {
				String[] delims;
				delims = output.trim().split(" ");

				int id = -1;
				String price = delims[delims.length-1];
				double aktPrice = 0d;
				try {
					id = Integer.parseInt(delims[0].substring(0, delims[0].length()-1));
					if(!price.equals("null")) {
						aktPrice = Double.parseDouble(delims[delims.length-2]);
					}
				} catch (NumberFormatException e) {
					e.printStackTrace();
				}
//				if(id == -1) return;


				BidObject bidobject = new BidObject(id, aktPrice);
				list.add(bidobject);
				output = client.response();
//				System.out.println(output);
			}
		}
		java.util.Random random = new java.util.Random();
		if(list.size()==0){
			return;
		}
		int newId = random.nextInt(list.size());

		client.sendCommand("!bid "+list.get(newId).getId()+" "+list.get(newId).getPrice()+20);
		System.out.println(client.response());
	}

}
